#!/usr/bin/python
# -*- coding: UTF-8 -*-

import time
import requests
import re
import json
import sys, os

class WeCom(object):
    """docstring for WeCom"""
    def __init__(self):
        self.__clearData()
        self.__loadConfig()

    def __clearAccessToken(self):
        self.__AccessToken = ""
        self.__AccessTokenExpired = 0

    def __clearData(self):
        self.__corpid = ""
        self.__corpsecret = ""
        self.__AgentId = ""
        self.__dataRecord = 0
        self.__clearAccessToken()

    def __loadConfig(self):
        try:
            with open("wecom.conf", "r+") as f:
                config = json.loads(f.read())
                self.__corpid = config['corpid']
                self.__corpsecret = config['corpsecret']
                self.__AgentId = config['AgentId']
                self.__dataRecord = config['dataRecord']
                self.__loadAccessToken()
        except Exception as e:
            print("Load WeCom config failed: " + str(e))
            self.__clearData()
            print("Creating sample config file")
            with open("wecom.conf", "w+") as f:
                # help_info = "# Find corpid at https://work.weixin.qq.com/wework_admin/frame#profile\r\n"
                # f.write(help_info)
                config = {
                    'corpid' : 'wwabcddzxdkrsdv',
                    'corpsecret' : 'vQT_03RDVA3uE6JDASDASDAiXUvccqV8mDgLdLI',
                    'AgentId' : 1000002,
                    'dataRecord' : 1
                }
                f.write(json.dumps(config, indent=2))

    def getTimestamp(self):
        return (int)(time.time())

    def getAccessToken(self):
        if self.__loadAccessToken():
            return True

        sample_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwabcddzxdkrsdv&corpsecret=vQT_03RDVA3uE6JDASDASDAiXUvccqV8mDgLdLI"
        url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
        params = {
            'corpid': f'{self.__corpid}',
            'corpsecret': f'{self.__corpsecret}'
        }

        try:
            # curl -G -d 'corpid=self.__corpid' -d 'corpsecret=self.__corpsecret' https://qyapi.weixin.qq.com/cgi-bin/gettoken
            timestampNow = self.getTimestamp()
            r = requests.get(url, params=params)
            r.encoding = 'utf-8'
            # print(r.text)
            try:
                accessToken_json = json.loads(r.text)
                error_code = (int)(accessToken_json['errcode'])
                if error_code != 0: # or error_code != '0':
                    error_msg = accessToken_json['errmsg']
                    print("Get accessToken failed, error code: " + str(error_code) + " (" + str(error_msg) + ")")
                    self.__clearAccessToken()
                    return False
                self.__AccessToken = accessToken_json['access_token']
                expires_in = (int)(accessToken_json['expires_in'])
                self.__AccessTokenExpired = timestampNow + expires_in
                print("accessToken: " + str(self.__AccessToken) + "\r\n" + "AccessTokenExpired: " + str(self.__AccessTokenExpired))
                self.__storeAccessToken()
                return True
            except Exception as e:
                print("Analyze accessToken json failed: " + str(e))
                self.__clearAccessToken()
                return False
        except Exception as e:
            print("Post to get accessToken failed: " + str(e))
            self.__clearAccessToken()
            return False

    def __checkAccessToken(self):
        if self.__AccessToken == "" or self.__AccessTokenExpired == 0 or self.__AccessTokenExpired < self.getTimestamp() + 5:
            return False
        return True

    def __storeAccessToken(self):
        if self.__dataRecord == 0:
            return False
        if not self.__checkAccessToken():
            return False
        with open("accessToken.data", "w+") as f:
            accessToken = {
                'AccessToken': self.__AccessToken,
                'AccessTokenExpired': self.__AccessTokenExpired
            }
            f.write(json.dumps(accessToken, indent=2))
            return True

    def __loadAccessToken(self):
        if self.__dataRecord == 0:
            return False
        try:
            with open("accessToken.data", "r+") as f:
                accessToken = json.loads(f.read())
                self.__AccessToken = accessToken['AccessToken']
                self.__AccessTokenExpired = accessToken['AccessTokenExpired']
                if not self.__checkAccessToken():
                    self.__clearAccessToken()
                    return False
                return True
        except Exception as e:
            print("Load accessToken failed: " + str(e))
            return False


    def senMsg(self, msg):
        if not self.__checkAccessToken():
            self.getAccessToken()
        sample_url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN"
        url = "https://qyapi.weixin.qq.com/cgi-bin/message/send"
        # url = "http://127.0.0.1:11080/"
        params = {
            'access_token': f'{self.__AccessToken}'
        }
        # AgentId = 1000002
        msg_data = {
            'touser' : '@all',
            'msgtype': 'text',
            'agentid' : f'{self.__AgentId}',
            'text' : {
                'content' : f'{msg}'
            },
            'safe' :0
        }
        try:
            r = requests.post(url, params=params, data=json.dumps(msg_data))
            # print(r.text)
            reslt_json = json.loads(r.text)
            error_code = (int)(reslt_json['errcode'])
            if error_code != 0:
                error_msg = accessToken_json['errmsg']
                print("Send WeCom msg failed, error code: " + str(error_code) + " (" + str(error_msg) + ")")
                return False
            return True
        except Exception as e:
            print("Send WeCom msg failed: " + str(e))
            return False



if __name__ == '__main__':
    we = WeCom()
    if len(sys.argv) == 2:
        print(we.senMsg(sys.argv[1]))
    else:
        print(we.senMsg("This is a test msg"))

